/* 
 * Copyright (c) 2019, CENTRIN.CIYUN.LTD. All rights reserved.
 */
package com.cory.admin.sys.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.cory.admin.sys.domain.AdminPrincipal;
import com.cory.boot.component.cache.RedisUtils;
import com.cory.boot.domain.bean.Result;
import com.cory.utils.web.CookieUtils;

/**
 * 登录拦截器
 * @author xiongcong
 * @date 2019-02-27
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
        AdminPrincipal user = (AdminPrincipal)request.getSession().getAttribute(AdminConstants.SESSION_USER_INFO);
        if (user != null) {
            String data = RedisUtils.get(AdminConstants.REDIS_PREFIX_TOKEN + user.getToken());
            if (data == null) {
                user = null;
                request.getSession().removeAttribute(AdminConstants.SESSION_USER_INFO);
            }
        }
        
        if (user != null) {
            String token = CookieUtils.getValue(request, AdminConstants.COOKIE_TOKEN);
            if (StringUtils.isNotBlank(token) && !token.equals(user.getToken())) {
                RedisUtils.del(AdminConstants.REDIS_PREFIX_TOKEN + user.getToken());
                user = null;
                request.getSession().removeAttribute(AdminConstants.SESSION_USER_INFO);
            }
        }
        
        if (user == null) {
            String xReq = request.getHeader("x-requested-with");
            if (StringUtils.isNotBlank(xReq) && "XMLHttpRequest".equalsIgnoreCase(xReq)) {
                response.setCharacterEncoding("UTF-8");  
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().append(JSONObject.toJSONString(Result.fail("会话已失效，请重新登录")));
                return false;
            }
            
            String msg = AdminConstants.MAP_LOGIN_TIP_MSG.get(request.getSession().getId());
            if (StringUtils.isNotBlank(msg)) {
                AdminConstants.MAP_LOGIN_TIP_MSG.remove(request.getSession().getId());
                request.getSession().setAttribute(AdminConstants.SESSION_LOGIN_MSG, msg);
            }
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
        
        // 默认密码，强制修改密码
        String requestURI = request.getRequestURI();
        if (requestURI.indexOf("portal") < 0 && requestURI.indexOf("/admin/sys/pwd") < 0 && request.getSession().getAttribute(AdminConstants.SESSION_DEFAULT_PWD) != null) {
            response.sendRedirect(request.getContextPath() + "/admin/sys/pwd/modify");
        }
        
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {}
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) throws Exception {}
}
